// pages/dayReport/dayReport.js
const util = require('../../utils/util.js')
const call = require("../../utils/request.js");
const MONTHS = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May.', 'June.', 'July.', 'Aug.', 'Sept.', 'Oct.', 'Nov.', 'Dec.'];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    timer: null,
    nowData: '',
    te: [],
    dailyFlag: 0,
    year: new Date().getFullYear(), // 年份
    month: new Date().getMonth() + 1, // 月份
    day: new Date().getDate(),
    pickDate_days_style: [],
    temp: '暂无数据',
    winHeight: "",
    pre_result: 0,
    embryoNum: 0,
    weekType: true,
    resultDate: "2018-01-01",
    removeDate: "2018-01-01",
    images: [],
    tempFilePaths: '',
    imgUpload: [],
    tempFilePaths: '',
    imgNum: 0,
    imgStr: '',
    hostUrl: call.hostUrl,
    projectId: '',
    dailyId: '',
    dailyDesc: '',
    reportDate: '',
    perType: wx.getStorageSync('LOGINDATA').perType,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let DATA = util.formatDate(new Date())
    console.log(DATA)
    console.log(options)
    that.setData({
      resultDate: DATA,
      removeDate: DATA,
      dailyId: options.dailyId,
      projectId: options.projectId,
      reportDate: options.reportDate
    })

    if (options.reportDate) {
      let str = new Date(options.reportDate)
      that.setData({
        year: str.getFullYear(),
        month: str.getMonth() + 1,
        day: str.getDate()
      })
    }
    const days_count = new Date(that.data.year, that.data.month, 0).getDate();
    let pickDate_days_style = new Array;
    for (let i = 1; i <= days_count; i++) {
      const date = new Date(that.data.year, that.data.month - 1, i);
      if (date.getDay() == 0) {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#F96C31'
        });
      } else if (date.getDay() == 6) {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#F96C31'
        });
      } else if (i == that.data.day) {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#fff',
          background: '#36ADED',
        });
      } else {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#000'
        });
      }
    }
    let te = that.data.te;
    for (let i = 0; i < te.length; i++) {
      let day = te[i].time.substring(te[i].time.length - 2)
      let month = te[i].time.split("-")[1];
      if (month == that.data.month) {
        pickDate_days_style.push({
          month: 'current',
          day: day,
          color: '#fff',
          background: '#FADBE3',
        })
      }
    }

    that.setData({
      pickDate_days_style: pickDate_days_style
    });

    if (options.dailyId) {
      that.getData()
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  getData() {
    // 获取日报详情
    let that = this
    let data = {
      dailyId: that.data.dailyId
    }
    call.httpService("/daily/dailyId", data, "post", (res) => {
        if (res.code === 0) {
          console.log(res.data.dailyDesc)
          that.setData({
            imgUpload: res.data.picturelist,
            dailyDesc: res.data.dailyDesc,
            images: res.data.picturelist,
            dailyFlag: res.data.dailyFlag
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
        wx.hideLoading();
      },
      (err) => {
        console.log(err)
        wx.hideLoading();
      }
    );
  },

  dayClick: function (event) {
    // 点击日历
    let that = this;
    let Date = event.detail.year + '-' + event.detail.month + '-' + event.detail.day;
    if (event.detail.day < 10) {
      Date = event.detail.year + '-' + event.detail.month + '-0' + event.detail.day;
    }
    that.setData({
      nowData: Date,
    })
    let pickDate_days_style = that.data.pickDate_days_style;

    if (that.data.Daif > 0) {
      pickDate_days_style.pop();
    }

    pickDate_days_style.push({
      month: 'current',
      day: event.detail.day,
      color: '#fff',
      background: '#36ADED',
    });

    that.setData({
      Daif: 1,
      pickDate_days_style: pickDate_days_style
    })

    that.getDateDayReport()

  },
  //图片选择
  chooseImage() {
    let that = this;
    wx.chooseImage({
      sizeType: ['original'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: function (res) {
        console.log(res)
        for (var i = 0, len = res.tempFilePaths.length; i < len; i++) {
          console.log(res.tempFilePaths[i])
          wx.uploadFile({
            url: that.data.hostUrl + '/common/upload',
            filePath: res.tempFilePaths[i],
            name: 'files',
            dataType: 'application/json;charset=utf-8',
            header: {
              "content-type": "multipart/form-data",
              "cookie": wx.getStorageSync('header').cookie
            },
            success(res) {
              if (res.header['Set-Cookie']) {
                let header = {
                  "content-type": "application/json;charset=UTF-8",
                  "cookie": res.header['Set-Cookie'].split(';')[0]
                }
                wx.setStorage({
                  key: "header",
                  data: header
                })
              }

              if (res.statusCode == 200) {
                console.log(res.data)
                var data = JSON.parse(res.data)
                wx.showToast({
                  title: data.msg,
                  icon: 'none',
                  duration: 2000
                })
                that.setData({
                  images: that.data.images.concat(data.data)
                });
                let imageUrl = that.data.images
                let imageList = that.data.imgUpload.concat(data.data);
                let imageUrls = imageUrl.length <= 9 ? imageUrl : imageUrl.slice(0, 10);
                let imageLists = imageList.length <= 9 ? imageList : imageList.slice(0, 10);
                that.setData({
                  images: imageUrls,
                  tempFilePaths: imageUrls,
                  imgNum: imageUrls.length,
                  imgUpload: imageLists
                });
              } else {
                console.log(res);
              }
            },
            fail(err) {
              console.log(err)
            }
          })
        }

      }
    })
  },
  //图片删除
  removeImage(e) {
    let that = this;
    const idx = e.target.dataset.idx
    that.data.images.splice(idx, 1);
    that.data.imgUpload.splice(idx, 1);
    that.setData({
      images: that.data.images,
      imgUpload: that.data.imgUpload,
      imgNum: that.data.images.length
    });
  },
  //预览图片
  handleImagePreview(e) {
    const idx = e.target.dataset.idx
    let urls = []
    this.data.images.forEach((item) => {
      urls.push(this.data.hostUrl + item)
    })
    wx.previewImage({
      current: urls[idx],
      urls: urls,
    })
  },
  //上传图片
  uploadImg: function () {
    let that = this;
    let imgList = "";
    for (var i = 0, len = that.data.imgUpload.length; i < len; i++) {
      imgList += that.data.imgUpload[i] + ';'
    }
    that.setData({
      imgStr: imgList
    });
  },
  titleBind(e) {
    // 日报说明
    this.setData({
      dailyDesc: e.detail.value
    });
  },
  save() {
    // 提交日报
    let that = this;
    let data = {};
    if (!that.data.dailyId) {
      data = {
        ctcId: that.data.projectId,
        picturelist: that.data.imgUpload,
        dailyDesc: that.data.dailyDesc,
      }
      call.httpService("/daily/add", data, "post", (res) => {
          if (res.code === 0) {
            wx.showToast({
              title: '日报已上传',
              icon: "none",
            });

            that.data.timer = setTimeout(
              function () {
                wx.switchTab({
                  url: '/pages/my/my'
                })
              }, 2000);

          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
          wx.hideLoading();
        },
        (err) => {
          console.log(err)
          wx.hideLoading();
        }
      );
    } else {
      data = {
        picturelist: that.data.imgUpload,
        dailyDesc: that.data.dailyDesc,
        dailyId: that.data.dailyId
      }
      call.httpService("/daily/modify", data, "post", (res) => {
          wx.showToast({
            title: '日报已修改',
            icon: "none",
          });
          if (res.code === 0) {
            that.data.timer = setTimeout(
              function () {
                wx.switchTab({
                  url: '/pages/my/my'
                })
              }, 2000);
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
          wx.hideLoading();
        },
        (err) => {
          console.log(err)
          wx.hideLoading();
        }
      );
    }
  },
  getDateDayReport() {
    // 根据日期获取日报详情
    let that = this
    let data = {
      ctcId: that.data.projectId,
      currentDate: that.data.nowData
    }
    call.httpService("/daily/search", data, "post", (res) => {
        if (res.code === 0) {
          that.setData({
            imgUpload: res.data.picturelist,
            dailyDesc: res.data.dailyDesc,
            images: res.data.picturelist,
            dailyFlag: res.data.dailyFlag
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
        wx.hideLoading();
      },
      (err) => {
        console.log(err)
        wx.hideLoading();
      }
    );
  },

  //前一个月
  prevMonth: function (event) {
    let that = this
    that.setData({
      year: event.detail.currentYear,
      month: event.detail.currentMonth
    })
    let te = that.data.te;
    let pickDate_days_style = new Array;
    const days_count = new Date(that.data.year, that.data.month, 0).getDate();
    for (let i = 1; i <= days_count; i++) {
      const date = new Date(that.data.year, that.data.month - 1, i);
      pickDate_days_style.push({
        month: 'current',
        day: i,
        color: '#B69EED'
      });
    }

    for (let i = 1; i <= days_count; i++) {
      const date = new Date(that.data.year, that.data.month - 1, i);
      if (date.getDay() == 0) {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#F96C31'
        });
      } else if (date.getDay() == 6) {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#F96C31'
        });
      } else {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#000'
        });
      }
    }
    if (that.data.month == (new Date().getMonth() + 1)) {
      pickDate_days_style.push({
        month: 'current',
        day: new Date().getDate(),
        color: '#fff',
        background: '#36ADED',
      })
    }
    for (let i = 0; i < te.length; i++) {
      let day = te[i].time.substring(te[i].time.length - 2)
      let month = te[i].time.split("-")[1];
      if (month == event.detail.currentMonth) {
        pickDate_days_style.push({
          month: 'current',
          day: day,
          color: '#fff',
          background: '#36ADED',
        })
      }
    }
    that.setData({
      Daif: 0,
      pickDate_days_style: pickDate_days_style
    })
  },

  //下一个月
  nextMonth: function (event) {
    let that = this
    that.setData({
      year: event.detail.currentYear,
      month: event.detail.currentMonth
    })
    let te = that.data.te;
    let pickDate_days_style = new Array;
    const days_count = new Date(that.data.year, that.data.month, 0).getDate();
    for (let i = 1; i <= days_count; i++) {
      const date = new Date(that.data.year, that.data.month - 1, i);
      pickDate_days_style.push({
        month: 'current',
        day: i,
        color: '#B69EED'
      });
    }
    for (let i = 1; i <= days_count; i++) {
      const date = new Date(that.data.year, that.data.month - 1, i);
      if (date.getDay() == 0) {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#F96C31'
        });
      } else if (date.getDay() == 6) {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#F96C31'
        });
      } else {
        pickDate_days_style.push({
          month: 'current',
          day: i,
          color: '#000'
        });
      }
    }
    if (that.data.month == (new Date().getMonth() + 1)) {
      pickDate_days_style.push({
        month: 'current',
        day: new Date().getDate(),
        color: '#fff',
        background: '#36ADED',
      })
    }
    for (let i = 0; i < te.length; i++) {
      let day = te[i].time.substring(te[i].time.length - 2)
      let month = te[i].time.split("-")[1];
      if (month == event.detail.currentMonth) {
        pickDate_days_style.push({
          month: 'current',
          day: day,
          color: '#fff',
          background: '#36ADED',
        })
      }
    }
    that.setData({
      Daif: 0,
      pickDate_days_style: pickDate_days_style
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearTimeout(this.data.timer)
    if (this.data.perType == 1) {
      wx.reLaunch({
        url: '/pages/my/my'
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})